package com.bonc.ioc.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.bonc.ioc.dao.DataAssetAssociationDao;
import com.bonc.ioc.dao.DataAssetDao;
import com.bonc.ioc.model.DataAssetInfo;
import com.bonc.ioc.service.IDataAssetAssociationService;
import com.bonc.ioc.util.SameTimeUtil;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

/**
 * @author ZhangXu
 * @date 2021/4/19 10:20
 */
@Service
public class DataAssetAssociationServiceImpl extends EsServiceImpl implements IDataAssetAssociationService {
    private static final Logger log = LoggerFactory.getLogger(DataAssetAssociationServiceImpl.class);

    @Resource
    private DataAssetAssociationDao dataAssetAssociationDao;

    @Resource
    private DataAssetDao dataAssetDao;

    @Override
    public void updateAssociation(Long id) {
        List<DataAssetInfo> association = dataAssetAssociationDao.selectAssociation(id);
        log.info("更新数据关联关系 当前关系={}", JSON.toJSONString(association));
        if (!association.isEmpty()) {
            Date updateTime = association.get(0).getUpdateTime();
            boolean flag = SameTimeUtil.isSameTime(updateTime, new Date(), SameTimeUtil.DAY);
            if (flag) {
                return;
            }
        }
        DataAssetInfo dataAssetInfo = dataAssetDao.selectDataDetailById(id);
        log.info("更新数据关联关系 目标数据={}", JSON.toJSONString(dataAssetInfo));
        if (dataAssetInfo != null) {
            saveAssociation(dataAssetInfo);
        }
    }

    private void saveAssociation(DataAssetInfo param) {
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder builder = QueryBuilders.boolQuery();
        if (StringUtils.isNotBlank(param.getIntroduction())) {
            builder.should(QueryBuilders.matchQuery("introduction", param.getIntroduction()));
        }
        if (StringUtils.isNotBlank(param.getDescription())) {
            builder.should(QueryBuilders.matchQuery("description", param.getDescription()));
        }
        if (StringUtils.isNotBlank(param.getKeyWords())) {
            builder.should(QueryBuilders.matchQuery("key_words", param.getKeyWords()));
        }
        searchSourceBuilder.query(builder);

        //创建并设置SearchRequest对象
        SearchRequest searchRequest = new SearchRequest();
        //设置request要搜索的索引和类型
        searchRequest.indices("data_assets");
        //设置SearchSourceBuilder查询属性
        searchRequest.source(searchSourceBuilder);
        log.info("ES检索命令 SearchSourceBuilder={}", searchSourceBuilder.toString());
        SearchResponse searchResponse = null;
        List<DataAssetInfo> dataAssetList = new LinkedList<>();
        try {
            searchResponse = client.search(searchRequest, COMMON_OPTIONS);
        } catch (IOException e) {
            e.printStackTrace();
        }
        assert searchResponse != null;
        SearchHit[] hits = searchResponse.getHits().getHits();
        Arrays.stream(hits).forEach(hit -> {
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            DataAssetInfo dataAssetInfo = BeanUtil.mapToBean(sourceAsMap, DataAssetInfo.class, true);
            if (!param.getId().equals(dataAssetInfo.getId())) {
                dataAssetList.add(dataAssetInfo);
            }
        });
        for (int i = 0; i < dataAssetList.size(); i++) {
            if (i == 8) {
                break;
            }
            int flag = dataAssetAssociationDao.updateAssociation(param.getId(), dataAssetList.get(i).getId(), i + 1);
            if (flag == 0) {
                dataAssetAssociationDao.addAssociation(param.getId(), dataAssetList.get(i).getId(), i + 1);
            }
        }
    }

    @Override
    public List<DataAssetInfo> queryAssociation(Long id) {
        return dataAssetAssociationDao.selectAssociation(id);
    }

}